#include "vcpkginstalldialog.h"
#include "config/config.h"
#include "ui_vcpkginstalldialog.h"

#include <QFileInfo>

VCPkgInstallDialog::VCPkgInstallDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::VCPkgInstallDialog)
{
    ui->setupUi(this);

    connect(&m_process, qOverload<int>(&QProcess::finished), this, [this](int exitCode)
    {
        if (exitCode == 0)
        {
            emit installed();
            setWindowTitle("vcpkg 安装完成: " + m_installPkg);
        }
    });

    connect(&m_process, &QProcess::readyRead, this, [this]()
    {
        QString output = m_process.readAllStandardOutput();
        ui->vcpkg_install_content->appendPlainText(output);
    });
}

VCPkgInstallDialog::~VCPkgInstallDialog()
{
    delete ui;
}

QString VCPkgInstallDialog::installPkg() const
{
    return m_installPkg;
}

void VCPkgInstallDialog::setInstallPkg(const QString &newInstallPkg)
{
    m_installPkg = newInstallPkg;
}

void VCPkgInstallDialog::start()
{
    if (Config::getAppCMakeConfig().isEmpty() == false)
    {
        ui->vcpkg_install_content->setPlainText("-- cmake --version -- \n");

        auto dir = QFileInfo(Config::getAppCMakeConfig()).absolutePath();
        qputenv("PATH", qEnvironmentVariable("PATH").prepend(dir + ":").toUtf8());

        // m_process.setEnvironment(QStringList() << qEnvironmentVariable("PATH"));
        QProcess process;
        process.setProgram("cmake");
        process.setArguments(QStringList() << "--version");
        process.start();
        process.waitForFinished();

        ui->vcpkg_install_content->appendPlainText(process.readAllStandardOutput() + "\n");
    }

    ui->vcpkg_install_content->appendPlainText("-- vcpkg install " + m_installPkg + " -- \n");
    m_process.setProgram(Config::getAppVCPkgConfig());
    m_process.setArguments(QStringList() << "install" << m_installPkg);
    m_process.start();
}
